package com.jingming.consult.network.utils;

import android.content.Context;


import com.jingming.consult.bean.BaseBean;

import java.lang.reflect.ParameterizedType;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;


/**
 * 泛型方式
 *
 * @param <T>
 */
public abstract class NetGenericityObserver<T> extends RxNetObserver<T> implements Observer<BaseBean<T>> {

    public NetGenericityObserver(@NonNull Context context) {
        super(context);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public final void onSubscribe(Disposable disposable) {
        try {
            onSubscribed(disposable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public final void onNext(@NonNull BaseBean<T> info) {
        if (info == null) {
            try {
                onFail("onNext method parameter is empty");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        if (info.getCode() == RESPONSE_CODE_OK) {
            try {
                if (info.getResult() != null) {
                    onSuccess(info.getResult(), info.getMessage());
                } else if (info.getResult() != null) {
                    onSuccess(info.getResult(), info.getMessage());
                } else {
                    try {
                        ParameterizedType ptype = (ParameterizedType) this.getClass().getGenericSuperclass();
                        Class clazz = (Class<T>) ptype.getActualTypeArguments()[0];
                        T o = (T) clazz.newInstance();
                        onSuccess(o, "暂无数据");
                    } catch (Exception e) {
                        onSuccess(null, "解析错误");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            //对服务器返回的通用问题的统一拦截处理
            if (con != null && con.get() != null) {
//                try {
//                    DeviceInfo.analysisCode(con.get(), info.getCode(), info.getErrorMsg());
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }
            try {
                onFail(info.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public final void onError(@NonNull Throwable t) {
        error(t);
    }

}
